package com.ocom.accesservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ocom.accesservice.controller.AccessController;
import com.ocom.accesservice.dao.IDaoGroupPer;
import com.ocom.accesservice.dao.IDaoPersonnelInfo;
import com.ocom.accesservice.service.AreaInfoService;
import com.ocom.accesservice.service.GroupInfoService;
import com.ocom.accesservice.service.GroupPerService;
import com.ocom.accesservice.service.WhiteRecodeService;
import com.ocom.common.entity.access.EntityMjAreaInfo;
import com.ocom.common.entity.access.EntityMjGroupInfo;
import com.ocom.common.entity.access.EntityMjGroupPer;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.enums.DataSourceEnum;
import com.ocom.common.enums.MasterSlaveEnum;
import com.ocom.common.request.access.GetGroupPerReq;
import com.ocom.common.request.wx.UserAccessPageSetAccessRequest;
import com.ocom.common.utils.StringUtils;
import com.ocom.common.vo.AccessListVo;
import com.ocom.common.vo.DelAreaVo;
import com.ocom.common.vo.UserAccessListVo;
import com.ocom.mysql.aspect.DataSourceAspect;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Slf4j
@Service
public class GroupPerServiceImpl extends ServiceImpl<IDaoGroupPer, EntityMjGroupPer> implements GroupPerService {

    Logger logger= LoggerFactory.getLogger(AccessController.class);


    @Autowired
    IDaoPersonnelInfo personnelInfo;

    @Autowired
    private IDaoGroupPer daoGroupPer;

    @Autowired
    AreaInfoService areaInfoService;

    @Autowired
    GroupInfoService groupInfoService;

    @Autowired
    WhiteRecodeService whiteRecodeService;

    @DataSourceAspect(type= DataSourceEnum.PART_DB,companyId = "comId",isMaster = MasterSlaveEnum.SLAVE)
    @Override
    public Integer CountPid(Long areaId, Long comId) {
        QueryWrapper<EntityMjGroupPer> wrapper = new QueryWrapper<>();
        wrapper.eq("area_id", areaId);
        return daoGroupPer.selectCount(wrapper);
    }

    /**
     * 移除区域
     * */
    @DataSourceAspect(type= DataSourceEnum.PART_DB,companyId = "companyID",isMaster = MasterSlaveEnum.MASTER)
    @Transactional
    @Override
    public void RemoveArea(DelAreaVo delAreaVo, Long companyID) {
        QueryWrapper<EntityMjGroupPer> query = Wrappers.query();
        if (StringUtils.isNotNull(delAreaVo.getComId())){
            query.eq("com_id",delAreaVo.getComId());
        }
        if (StringUtils.isNotNull(delAreaVo.getAreaId())){
            query.eq("area_id",delAreaVo.getAreaId());
        }
        daoGroupPer.delete(query);

    }

    @DataSourceAspect(type= DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.SLAVE)
    @Override
    public List<EntityMjGroupPer> getList(Long companyId, Long pId) {
        QueryWrapper<EntityMjGroupPer> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("com_id",companyId);
        if(pId!=0L){
            queryWrapper.eq("p_id",pId);
        }
        return this.list(queryWrapper);
    }


    @DataSourceAspect(type= DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.SLAVE)
    @Override
    public List<UserAccessListVo> getAccessListByArea(Long companyId, Long areaNo) {
        QueryWrapper<EntityMjGroupPer> queryWrapper=new QueryWrapper<>();

        if(areaNo!=null && areaNo>0){
            queryWrapper.eq("area_id",areaNo);
        }else{
            queryWrapper.eq("com_id",companyId);
        }
        List<EntityMjGroupPer>  list= this.list(queryWrapper);
        if(list.size()<=0){
            return null;
        }
        List<UserAccessListVo> res= new ArrayList<>();
        for (EntityMjGroupPer entityMjGroupPer:list){
            UserAccessListVo userAccessListVo=new UserAccessListVo();
            userAccessListVo.setUserId(entityMjGroupPer.getPId());
            userAccessListVo.setRoleI(entityMjGroupPer.getGroupNo());


            QueryWrapper<EntityPersonnelInfo> personnelInfoQueryWrapper=new QueryWrapper<>();
            personnelInfoQueryWrapper.eq("p_id",entityMjGroupPer.getPId());
            personnelInfoQueryWrapper.last("limit 1");
            EntityPersonnelInfo entityPersonnelInfo=personnelInfo.selectOne(personnelInfoQueryWrapper);
            if(entityPersonnelInfo!=null){
                userAccessListVo.setUserName(entityPersonnelInfo.getPName());
            }

            QueryWrapper<EntityMjGroupInfo> mjGroupInfoQueryWrapper=new QueryWrapper<>();
            mjGroupInfoQueryWrapper.eq("group_no",entityMjGroupPer.getGroupNo());
            if(entityMjGroupPer.getGroupNo()<17L){
                mjGroupInfoQueryWrapper.eq("com_id",entityMjGroupPer.getComId());
            }else{
                mjGroupInfoQueryWrapper.eq("area_id",entityMjGroupPer.getAreaId());
            }
            mjGroupInfoQueryWrapper.last("limit 1");
            EntityMjGroupInfo mjGroupInfo=groupInfoService.getOne(mjGroupInfoQueryWrapper);
            if(mjGroupInfo!=null){
                userAccessListVo.setGroupName(mjGroupInfo.getGroupName());
            }
            res.add(userAccessListVo);
        }
        return  res;
    }


    @DataSourceAspect(type= DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.MASTER)
    @Override
    public EntityMjGroupPer changeAccess(Long companyId, UserAccessPageSetAccessRequest request) {
        QueryWrapper<EntityMjGroupInfo> entityMjGroupInfoQueryWrapper=new QueryWrapper<>();
        entityMjGroupInfoQueryWrapper.eq("group_no",request.getRoleI());
        entityMjGroupInfoQueryWrapper.eq("area_id",request.getAreaNo());
        entityMjGroupInfoQueryWrapper.last("limit 1");
        EntityMjGroupInfo entityMjGroupInfo=groupInfoService.getOne(entityMjGroupInfoQueryWrapper);


        QueryWrapper<EntityMjGroupPer> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("area_id",request.getAreaNo());
        queryWrapper.eq("p_id",request.getUserId());
        queryWrapper.eq("com_id",request.getCompanyId());
        queryWrapper.last("limit 1");
        EntityMjGroupPer entityMjGroupPer=this.getOne(queryWrapper);

        if(request.getRoleI()==0){
            //删除 权限
            QueryWrapper<EntityMjGroupPer>  queryWrapper2=new QueryWrapper<>();
            queryWrapper2.eq("area_id",request.getAreaNo());
            queryWrapper2.eq("p_id",request.getUserId());
            queryWrapper2.eq("com_id",request.getCompanyId());
            this.remove(queryWrapper2);
            whiteRecodeService.delPerson(request.getCompanyId(),request.getAreaNo(),request.getUserId());
            return null;
        }else{
            whiteRecodeService.addPerson(companyId,request.getAreaNo(),request.getUserId());
            if(entityMjGroupPer==null){
                EntityMjGroupPer entityMjGroupPer1=new EntityMjGroupPer();
                entityMjGroupPer1.setPId(request.getUserId());
                entityMjGroupPer1.setComId(request.getCompanyId());
                entityMjGroupPer1.setAreaId(request.getAreaNo());
                entityMjGroupPer1.setGroupNo(request.getRoleI());
                entityMjGroupPer1.setCreateTime(new Date());
                entityMjGroupPer1.setUpdateTime(new Date());
                this.save(entityMjGroupPer1);
                return entityMjGroupPer1;
            }else{
                UpdateWrapper<EntityMjGroupPer> updateWrapper=new UpdateWrapper<>();
                updateWrapper.eq("area_id",request.getAreaNo());
                updateWrapper.eq("p_id",request.getUserId());
                updateWrapper.eq("com_id",request.getCompanyId());
                updateWrapper.set("group_no",request.getRoleI());
                this.update(updateWrapper);
                entityMjGroupPer.setGroupNo(request.getRoleI());
                return  entityMjGroupPer;
            }
        }

    }


    @DataSourceAspect(type= DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.SLAVE)
    @Override
    public List<AccessListVo> getListByUid(Long companyId, Long pId) {
        QueryWrapper<EntityMjGroupPer> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("com_id",companyId);
        if(pId!=0L){
            queryWrapper.eq("p_id",pId);
        }

        List<EntityMjGroupPer> list= this.list(queryWrapper);

        List<AccessListVo> res=new ArrayList<>();
        if(list.size()>0){
            for (EntityMjGroupPer entityMjGroupPer:list){
                AccessListVo accessListVo=new AccessListVo();
                accessListVo.setAreaNo(entityMjGroupPer.getAreaId());
                accessListVo.setRoleI(entityMjGroupPer.getGroupNo());

                QueryWrapper<EntityMjAreaInfo> areaInfoQueryWrapper=new QueryWrapper<>();
                areaInfoQueryWrapper.eq("area_id",entityMjGroupPer.getAreaId());
                areaInfoQueryWrapper.last("limit 1");
                EntityMjAreaInfo entityMjAreaInfo=areaInfoService.getOne(areaInfoQueryWrapper);
                if(entityMjAreaInfo!=null){
                    accessListVo.setDoorArea(entityMjAreaInfo.getAreaName());
                    accessListVo.setRegionId(entityMjAreaInfo.getRegionId());
                }

                QueryWrapper<EntityMjGroupInfo> groupInfoQueryWrapper=new QueryWrapper<>();
                groupInfoQueryWrapper.eq("group_no",entityMjGroupPer.getGroupNo());
                if(entityMjGroupPer.getGroupNo()<17L){
                    groupInfoQueryWrapper.eq("com_id",entityMjGroupPer.getComId());
                }else{
                    groupInfoQueryWrapper.eq("area_id",entityMjGroupPer.getAreaId());
                }
                groupInfoQueryWrapper.last("limit 1");
                EntityMjGroupInfo groupInfo=groupInfoService.getOne(groupInfoQueryWrapper);
                if(groupInfo!=null){
                    accessListVo.setGroupName(groupInfo.getGroupName());
                }
                res.add(accessListVo);
            }
        }
        return res;
    }


    @DataSourceAspect(type= DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.SLAVE)
    @Override
    public List<UserAccessListVo> getUserAccessListByArea(Long companyId, Long areaNo, Long deptId) {
        QueryWrapper<EntityPersonnelInfo> personnelInfoQueryWrapper=new QueryWrapper<>();
        personnelInfoQueryWrapper.eq("com_id",companyId);
        //TODO 部门查询

        List<EntityPersonnelInfo> list=personnelInfo.selectList(personnelInfoQueryWrapper);
        if(list==null || list.size()==0){
            return null;
        }

        QueryWrapper<EntityMjGroupInfo> groupInfoQueryWrapper=new QueryWrapper<>();
        groupInfoQueryWrapper.eq("com_id",companyId);
        List<EntityMjGroupInfo> entityMjGroupInfoList=groupInfoService.list(groupInfoQueryWrapper);
        Map<Long,String> mapKV=new HashMap<>();
        if(entityMjGroupInfoList!=null){
            for (EntityMjGroupInfo entityMjGroupInfo:entityMjGroupInfoList){
                mapKV.put(entityMjGroupInfo.getGroupNo(),entityMjGroupInfo.getGroupName());
            }
        }

        List<UserAccessListVo> res= new ArrayList<>();
        for (EntityPersonnelInfo entityPersonnelInfo1:list){
            if(entityPersonnelInfo1.getStatus()!=0){
                continue;
            }
            UserAccessListVo userAccessListVo=new UserAccessListVo();
            userAccessListVo.setUserId(entityPersonnelInfo1.getPId());
            userAccessListVo.setUserName(entityPersonnelInfo1.getPName());
            userAccessListVo.setRoleI(0L);
            userAccessListVo.setGroupName("");

            QueryWrapper<EntityMjGroupPer> entityMjGroupPerQueryWrapper=new QueryWrapper<>();
            entityMjGroupPerQueryWrapper.eq("com_id",companyId);
            entityMjGroupPerQueryWrapper.eq("p_id",entityPersonnelInfo1.getPId());
            entityMjGroupPerQueryWrapper.eq("area_id",areaNo);
            entityMjGroupPerQueryWrapper.last("limit 1");
            EntityMjGroupPer entityMjGroupPer=this.getOne(entityMjGroupPerQueryWrapper);
            if(entityMjGroupPer!=null){
                userAccessListVo.setRoleI(entityMjGroupPer.getGroupNo());
                userAccessListVo.setGroupName(mapKV.get(entityMjGroupPer.getGroupNo()));
            }
            res.add(userAccessListVo);
        }
        return  res;


    }

    //从mj_group_per表查找com_id=companyId、p_id=userId、group_no>0的记录。
    @DataSourceAspect(type= DataSourceEnum.PART_DB,companyId = "comId",isMaster = MasterSlaveEnum.SLAVE)
    @Override
    public List<EntityMjGroupPer> getGroupPerInfo(Long comId, Long userId) {
        QueryWrapper<EntityMjGroupPer> query = Wrappers.query();
        query.eq("com_id",comId);
        query.eq("p_id",userId);
        query.gt("group_no",0);
        return daoGroupPer.selectList(query);
    }

    @Override
    @DataSourceAspect(type= DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.MASTER)
    public boolean removeUser(Long companyId, Long pId) {
        UpdateWrapper<EntityMjGroupPer> entityMjGroupPerQueryWrapper=new UpdateWrapper<>();
        entityMjGroupPerQueryWrapper.eq("com_id",companyId);
        entityMjGroupPerQueryWrapper.eq("p_id",pId);
        return this.remove(entityMjGroupPerQueryWrapper);
    }

    @Override
    @DataSourceAspect(type= DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.MASTER)
    public void removeWhiteUser(Long companyId,Long pId){
        logger.info("移除所有区域权限，companyId："+companyId.toString());
        logger.info("移除所有区域权限，pId："+pId.toString());

        //移除人员权限
        QueryWrapper<EntityMjGroupPer>  queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("p_id",pId);
        queryWrapper.eq("com_id",companyId);
        this.remove(queryWrapper);

        //删除 所有区域权限
        QueryWrapper<EntityMjAreaInfo>  queryWrapper2=new QueryWrapper<>();
        queryWrapper2.eq("com_id",companyId);
        List<EntityMjAreaInfo> list= areaInfoService.list(queryWrapper2);
        if(list!=null && list.size()>0){
            for (EntityMjAreaInfo areaInfo:list){
                whiteRecodeService.delPerson(companyId,areaInfo.getAreaId(),pId);
            }
        }
    }

    @Override
    @DataSourceAspect(type= DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.SLAVE)
    public PageInfo<EntityMjGroupPer> getGroupPerList(Long companyId, GetGroupPerReq req) {
        LambdaQueryWrapper<EntityMjGroupPer> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(EntityMjGroupPer::getComId,req.getComId());
        queryWrapper.in(EntityMjGroupPer::getAreaId,req.getAreaIds());
        queryWrapper.orderByAsc(EntityMjGroupPer::getPId);
        queryWrapper.groupBy(EntityMjGroupPer::getPId);
        PageHelper.startPage(req.getPage(),req.getSize());
        List<EntityMjGroupPer> pointInfoPageInfo=this.list(queryWrapper);
        PageInfo<EntityMjGroupPer> pageInfo=new PageInfo<>(pointInfoPageInfo);
        return pageInfo;
    }

}
